const express = require('express');
const { resolve } = require('path');
const { readFileSync, writeFileSync } = require('fs');
const bodyParser = require('body-parser');
const app = express();

app.use(
  bodyParser.urlencoded({
    extended: true
  })
);

app.use(bodyParser.json());

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,POST');
  next();
});

app.get('/get_comment_list', (req, res) => {
  const commentList = readComment();

  res.json({
    code: 0,
    msg: 'get comment list successfully!',
    data: commentList
  });
});

app.post('/set_comment_list', (req, res) => {
  const { comment } = req.body;
  // console.log(comment);
  //{id: '1677654493172', uid: '1', pid: '0', username: 'icy', comment: '111'}
  const commentList = readComment();
  commentList.unshift(comment);
  writeComment(commentList);

  res.json({
    code: 0,
    msg: 'set comment list successfully!',
    data: comment
  });
});

app.listen(8080, () => {
  console.log('Server started on 8080.');
});

function readComment() {
  return JSON.parse(
    readFileSync(resolve(__dirname, 'data/comments.json'), 'utf8') || '[]'
  );
}

function writeComment(data) {
  writeFileSync(resolve(__dirname, 'data/comments.json'), JSON.stringify(data));
}
